﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HaiFengShop.Tools.Utils
{
    /// <summary>
    /// 
    /// </summary>
    public class DateTimeExtensions
    {
        /// <summary>
        /// 转unix时间戳
        /// </summary>
        /// <param name="date"></param>
        /// <returns></returns>
        public static double ConvertToUnixTimestamp(DateTime date)
        {
            DateTime OLDtime = new DateTime(1970, 1, 1, 0, 0, 0, 0);
            TimeSpan diff = date.ToUniversalTime() - OLDtime;
            return Math.Floor(diff.TotalMilliseconds / 1000);
        }
        /// <summary>
        /// 将Unix时间戳转换为dateTime格式
        /// </summary>
        /// <param name="time"></param>
        /// <returns></returns>
        public static DateTime UnixTimeToDateTime(int time)
        {
            if (time < 0)
                throw new ArgumentOutOfRangeException("time is out of range");

            return TimeZoneInfo.ConvertTime(new DateTime(1970, 1, 1), TimeZoneInfo.Local).AddSeconds(time);
        }

        /// 将时间戳转换为YYYY-MM-DD字符串
        /// </summary>
        /// <param name="time"></param>
        /// <returns></returns>
        public static string UnixTimeToDateTimeYYMMDD(int time)
        {
            if (time < 0)
                throw new ArgumentOutOfRangeException("time is out of range");

            return TimeZoneInfo.ConvertTime(new DateTime(1970, 1, 1), TimeZoneInfo.Local).AddSeconds(time).ToShortDateString();
        }

        private static readonly object _lock = new object();

        /// <summary>
        /// 生成随即订单号
        /// </summary>
        /// <returns></returns>
        public static string GenerateOrderNumber()
        {
            lock (_lock)
            {
                Random ran = new Random();
                return DateTime.Now.ToString("yyyyMMddHHmmssfff") + ran.Next(100, 999).ToString();
            }
        }
    }
}
